﻿using System.Collections.ObjectModel;
using AddressManager.Common.Extension;
using AddressManager.Common.ViewModel;
using AddMan = AddressManager.Services.AddressManagerService;

namespace AddressManager.Business.ViewModels
{
    public class HomeViewModel : AbstractViewModel
    {
        readonly AddMan.AddressManagerWebServiceClient _addManService;

        public HomeViewModel()
        {
            Contacts = new ObservableCollection<AddMan.Contact>();

            _addManService = new AddMan.AddressManagerWebServiceClient("CustomBinding_AddressManagerWebService");
            _addManService.GetAllContactsCompleted += AddManServiceGetAllContactsCompleted;
        }

        #region DataBinding

        public ObservableCollection<AddMan.Contact> Contacts { get; set; }

        private AddMan.Contact _selectedContact;
        public AddMan.Contact SelectedContact
        {
            get { return _selectedContact; }
            set
            {
                SetProperty(this, x => x.SelectedContact, ref _selectedContact, value);
                RaisePropertyChanged(this, x => x.IsContactSelected);
            }
        }

        public bool IsContactSelected
        {
            get
            {
                return SelectedContact != null;
            }
        }

        #endregion

        #region Methods

        public void GetContacts()
        {
            _addManService.GetAllContactsAsync();
        }

        void AddManServiceGetAllContactsCompleted(object sender, AddMan.GetAllContactsCompletedEventArgs e)
        {

            Contacts.Clear();
            Contacts.AddAll(e.Result);

            OnGettingFinished();
        }

        #endregion
    }
}